package com.nxy.cpfsfe.util;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
  * xml和map相互转换的工具类
  * @author zhouxuke
  *
  */
public class XmlUtil {

    /**
     * @param message
     * @return
     */
    public static Map<String, String> xml2Map(String message) {
        Map<String, String> data = new LinkedHashMap<String, String>();
        Document doc = null;
        message = replaceStr(message);
     
        try {
            doc = DocumentHelper.parseText(message);     
        } catch (DocumentException e) {
            e.printStackTrace();
        }
       
        Element root = doc.getRootElement();
       
        //String path = "/" + root.getName();
        element2Map(root, data);

        return data;
    }
    private static void element2Map(Element node, Map<String, String> data) {
        if (node == null) {
            return;
        }

        if (node.elements().size() == 0)
            data.put(node.getUniquePath(), node.getText());

        List<Attribute> listAttr = node.attributes();//当前节点的所有属性的list
        for (Attribute attr : listAttr) {//遍历当前节点的所有属性
            data.put(attr.getUniquePath(), attr.getValue());
        }

        //递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();//所有一级子节点的list
        for (Element e : listElement) {//遍历所有一级子节点
            element2Map(e, data);//递归
        }
    }

    /**
     * 把map转换成xml
     *
     * @param map
     * @return
     */
    public static String map2Xml(Map<String, String> map) {
        String xml = "";
         //根据map用dom4j创建Document
        Document doc = DocumentHelper.createDocument();
        Iterator<Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> e = it.next();
            String key = e.getKey();
            String value = e.getValue();
            if (key.contains("@") == true)
            {
                String key1 = key.substring(0, key.indexOf("@"));
                String attr = key.substring(key.indexOf("@")+1, key.length());
                Element ele = DocumentHelper.makeElement(doc, key1);
                ele.addAttribute(attr, value);
            }
            else {
                Element ele = DocumentHelper.makeElement(doc, key);
                ele.setText(value);
            }
        }

        //格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setNewLineAfterDeclaration(true);
        format.setExpandEmptyElements(false);
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, format);
        try {
            writer.write(doc);
        } catch (IOException e) {
            e.printStackTrace();
        }
        xml = out.toString();
        xml = xml.replaceAll("\\[\\d*\\]", "");
        return xml;
    }
    /**
     * 把map转换成xml
     *
     * @param map
     * @return
     */
    public static String mapSO2Xml(Map<String, Object> map) {
    	StringBuffer buff = new  StringBuffer();
    	for(Map.Entry<String, Object> entry: map.entrySet()){
    		String key = entry.getKey();
    		Object value = entry.getValue();
    		buff.append("<").append(key).append(">");

    		if(value instanceof Map){
    			buff.append(mapSO2Xml((Map)value));
    		}else{
    			buff.append(value);
    		}
    		buff.append("</").append(key).append(">");

    	}
    	return buff.toString();
    }
    
  
    
    
    public static String getValByXPath(String msg,String xpath) {
		// TODO 自动生成的方法存根\	
    	msg = replaceStr(msg);
		Document doc = null;
		String str=null;
        try {
            doc = DocumentHelper.parseText(msg);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element root = doc.getRootElement();
        str = doc.selectSingleNode(xpath) != null ? doc.selectSingleNode(xpath).getText() : "";
        return str;


	}
    
    //根据节点获取该节点下的xml
    public static String getXmlByXPath(String msg,String xpath) {
		// TODO 自动生成的方法存根\	
		Document doc = null;

		msg = replaceStr(msg);
		String str=null;
        try {
            doc = DocumentHelper.parseText(msg);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element root = doc.getRootElement();
        str = doc.selectSingleNode(xpath) != null ? doc.selectSingleNode(xpath).asXML() : "";
        return str;


	}
    
    public static String replaceStr(String msg) {

    	String reg="<transaction(.*?)xmlns(.*?)\">";
    	msg = msg.replaceFirst(reg,"<transaction>");     	
    	return  msg;
    	 
    }

    /*特殊处理多节点为单节点,
     例：把/transaction/body/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/Ustrd[1]=/SttlmDt/2020-01-20
      处理为/transaction/body/FIToFICstmrCdtTrf/CdtTrfTxInf/RmtInf/SttlmDt=2020-01-20
    */
    public static Map formatXmlAttr(Map<String,Object> map,String attr) {

        Map<String, Object> mapTemp = new HashMap<String, Object>();
        String ustrdKey = "";
        String ustrdValue = "";
        for (String key : map.keySet()) {
            if (key.contains(attr) && map.get(key) != null) {
                if (map.get(key).toString().contains("/") && map.get(key).toString().split("/").length > 2) {
                    ustrdKey = key.substring(0, key.lastIndexOf("/") + 1) + map.get(key).toString().split("/")[1];
                    ustrdValue = map.get(key).toString().split("/")[2];
                    mapTemp.put(ustrdKey, ustrdValue);
                }
            }
            ustrdKey = "";
            ustrdValue = "";
        }
        map.putAll(mapTemp);
        return map;
    }

    /**
     * 获取匹配目标字符串
     * @param str
     * @param regex
     * @return
     */
    public static String getStr(String str,String regex) {
		// TODO 自动生成的方法存根		
		Pattern pat = Pattern.compile(regex);
		Matcher mat= pat.matcher(str);
		String st="";
		while(mat.find()){
			st = mat.group();
		}
		System.out.println(st);
		return st;
	}

    public static String getSysIdBySeqNb(String refseqNb){
        String sysId = refseqNb.substring(2,8);
        sysId = StringUtils.trimTrailingCharacter(sysId,'0');
        return sysId;
    }

  

}